<template>
  <a-modal
    title="编辑主机"
    :width="800"
    :visible="visible"
    @cancel="handleCancel"
    @ok="handleSubmit"
    :confirmLoading="confirmLoading"
    :destroyOnClose="true"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item v-bind="formItemLayout" label="主机名称" hasFeedback>
          <a-input
            v-decorator="['node', { rules: [{ required: true, message: '主机名称不能为空' }] }]"
            :maxLength="32"
            placeholder="请输入主机名称"
            disabled="disabled"
          />
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="主机地址" hasFeedback>
          <a-input
            v-decorator="['node_alias', { rules: [{ required: true, message: '主机地址不能为空' }] }]"
            :maxLength="20"
            placeholder="请输入主机地址"
            disabled="disabled"
          />
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="功能描述" hasFeedback>
          <a-input
            v-decorator="['node_func', {initialValue: '', rules: []}]"
            :maxLength="20"
            placeholder="请输入功能描述"
          />
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="业务应用" hasFeedback>
          <a-select
            class="selectshow"
            show-search
            :default-active-first-option="false"
            style="width: 100%"
            v-decorator="['app_name']"
            :show-arrow="false"
            allowClear
            mode="combobox"
            :autoClearSearchValue="true"
            placeholder="请选择业务应用"
          >
            <a-select-option v-for="(app, index) in appList" :key="index" :value="app.name">{{ app.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="所属平台" hasFeedback>
          <a-select
            class="selectshow"
            show-search
            :default-active-first-option="false"
            style="width: 100%"
            v-decorator="['pcs_name']"
            :show-arrow="false"
            allowClear
            mode="combobox"
            :autoClearSearchValue="true"
            placeholder="请选择所属平台"
          >
            <a-select-option v-for="(pcs, index) in pcsList" :key="index" :value="pcs.name">{{ pcs.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="组织机构" hasFeedback>
          <a-select
            class="selectshow"
            show-search
            :default-active-first-option="false"
            style="width: 100%"
            v-decorator="['org_name']"
            :show-arrow="false"
            allowClear
            mode="combobox"
            :autoClearSearchValue="true"
            placeholder="请选择组织机构"
          >
            <a-select-option v-for="(org, index) in orgList" :key="index" :value="org.name">{{ org.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="数据中心" hasFeedback>
          <a-select
            class="selectshow"
            show-search
            :default-active-first-option="false"
            style="width: 100%"
            v-decorator="['location']"
            :show-arrow="false"
            allowClear
            mode="combobox"
            :autoClearSearchValue="true"
            placeholder="请选择数据中心"
          >
            <a-select-option v-for="(loc, index) in locList" :key="index" :value="loc.name">{{ loc.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="操作系统类型" hasFeedback>
          <a-select
            class="selectshow"
            show-search
            :default-active-first-option="false"
            style="width: 100%"
            v-decorator="['os_type', {initialValue: ''}]"
            :show-arrow="false"
            allowClear
            mode="combobox"
            :autoClearSearchValue="true"
            placeholder="请选择操作系统类型"
          >
            <a-select-option v-for="(os_type, index) in osTypeList" :key="index" :value="os_type.name">{{ os_type.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="操作系统版本" hasFeedback>
          <a-input
            v-decorator="['os_level', {initialValue: ''}]"
            :maxLength="20"
            placeholder="请输入操作系统版本"
          />
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="纳管系统信息" hasFeedback>
          <a-select
            class="selectshow"
            show-search
            :default-active-first-option="false"
            style="width: 100%"
            v-decorator="['sub_system_name', {initialValue: ''}]"
            :show-arrow="false"
            allowClear
            mode="combobox"
            :autoClearSearchValue="true"
            placeholder="请选择纳管系统"
          >
            <a-select-option v-for="(sub, index) in subList" :key="index" :value="sub.name">{{ sub.name }}</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import { sqlSelect, sqlFindOne, sqlUpdate } from '@/api/sql'

export default {
  name: 'HostEditModal',

  data () {
    return {
      confirmLoading: false,
      visible: false,

      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 4 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 18 }
        }
      },

      form: this.$form.createForm(this),

      node: '',
      node_alias: '',
      result: {},

      /* 业务应用/所属平台/组织部门/数据中心/纳管系统列表: 动态 */
      appList: [],
      pcsList: [],
      orgList: [],
      locList: [],
      subList: []
    }
  },

  created () {
    this.osTypeList = [
      {
        name: 'Linux'
      },
      {
        name: 'Windows'
      }
    ]

    this.generateAppList()
    this.generatePcsList()
    this.generateOrgList()
    this.generateLocList()
    this.generateSubList()
  },

  computed: {
  },

  methods: {
    async init (node, nodeAlias) {
      this.node = node
      this.node_alias = nodeAlias

      // 显示弹框
      this.visible = true
      this.result = await this.getByPrimaryKey(node, nodeAlias)
      console.log('result', this.result)

      // 初始化form表单数据
      this.$nextTick(() => {
        this.form.setFieldsValue({
          node: this.result.node,
          node_alias: this.result.node_alias,
          node_func: this.result.node_func,
          app_name: this.result.app_name,
          pcs_name: this.result.pcs_name,
          org_name: this.result.org_name,
          location: this.result.location,
          os_type: this.result.os_type,
          os_level: this.result.os_level,
          sub_system_name: this.result.sub_system_name
        })
      })
    },

    async generateAppList () {
      this.data = await this.getAppList()
      const _this = this

      this.data.forEach(function (item) {
        _this.appList.push({
          'name': item.app_name
        })
      })
    },

    async generatePcsList () {
      this.data = await this.getPcsList()
      const _this = this

      this.data.forEach(function (item) {
        _this.pcsList.push({
          'name': item.pcs_name
        })
      })
    },

    async generateOrgList () {
      this.data = await this.getOrgList()
      const _this = this

      this.data.forEach(function (item) {
        _this.orgList.push({
          'name': item.org_name
        })
      })
    },

    async generateLocList () {
      this.data = await this.getLocList()
      const _this = this

      this.data.forEach(function (item) {
        _this.locList.push({
          'name': item.location_name
        })
      })
    },

    async generateSubList () {
      this.data = await this.getSubList()
      const _this = this

      this.data.forEach(function (item) {
        _this.subList.push({
          'name': item.sub_system_name
        })
      })
    },

    getAppList () {
      const params = {
        sql: `select * from cmdb.apps order by app_id asc`
      }
      return new Promise((resolve, reject) => {
        sqlSelect(params).then(
          (res) => {
            resolve(res)
          },
          (error) => {
            reject(error)
          }
        )
      })
    },

    getPcsList () {
      const params = {
        sql: `select * from cmdb.clouds order by pcs_id asc`
      }
      return new Promise((resolve, reject) => {
        sqlSelect(params).then(
          (res) => {
            resolve(res)
          },
          (error) => {
            reject(error)
          }
        )
      })
    },

    getOrgList () {
      const params = {
        sql: `select * from cmdb.orgs order by org_id asc`
      }
      return new Promise((resolve, reject) => {
        sqlSelect(params).then(
          (res) => {
            resolve(res)
          },
          (error) => {
            reject(error)
          }
        )
      })
    },

    getLocList () {
      const params = {
        sql: `select * from cmdb.locations order by location_id asc`
      }
      return new Promise((resolve, reject) => {
        sqlSelect(params).then(
          (res) => {
            resolve(res)
          },
          (error) => {
            reject(error)
          }
        )
      })
    },

    getSubList () {
      const params = {
        sql: `select * from cmdb.sub_system_info order by sub_system_id asc`
      }
      return new Promise((resolve, reject) => {
        sqlSelect(params).then(
          (res) => {
            resolve(res)
          },
          (error) => {
            reject(error)
          }
        )
      })
    },

    handleCancel () {
      // 取消弹框
      this.visible = false
    },

    handleSubmit () {
      const {
        form: { validateFields }
      } = this
      this.confirmLoading = true

      validateFields((errors, values) => {
        console.log('errors:', errors, 'val:', values)

        if (!errors) {
          this.verify(values.node, values.node_alias).then((res) => {
            console.log(res)
            if (!res.node) {
              this.$notification['error']({
                message: '提示',
                description: '主机信息不存在'
              })
              this.confirmLoading = false
            } else {
              this.update(values).then((response) => {
                this.visible = false
                this.confirmLoading = false
                this.$notification['success']({
                  message: '提示',
                  description: '主机信息更新成功！'
                })

                // 延迟发送事件，解决列表刷新还是老数据的问题
                setTimeout(() => {
                  this.$emit('ok', values)
                }, 1000)
              })
            }
          })
        } else {
          this.confirmLoading = false
        }
      })
    },

    /*
     * 修改数据
     */
    update (values) {
      var params = {
        sql: `update cmdb.hosts set node_func='${values.node_func}', app_name='${values.app_name}', pcs_name='${values.pcs_name}', org_name='${values.org_name}', location='${values.location}', os_type='${values.os_type}', os_level='${values.os_level}', sub_system_name='${values.sub_system_name}' where node='${this.result.node}' and node_alias='${this.result.node_alias}'`
      }
      return new Promise((resolve, reject) => {
        sqlUpdate(params).then(
          (res) => {
            resolve(res)
          },
          (error) => {
            reject(error)
          }
        )
      })
    },

    /*
     * 检查主机信息是否重复
     */
    verify (node, nodeAlias) {
      const params = {
        sql: `select * from cmdb.hosts where node='${node}' and node_alias='${nodeAlias}'`
      }
      return new Promise((resolve, reject) => {
        sqlFindOne(params).then(
          (res) => {
            resolve(res)
          },
          (error) => {
            reject(error)
          }
        )
      })
    },

    /*
     * 获取单条数据
     */
    getByPrimaryKey (node, nodeAlias) {
      const params = {
        sql: `select * from cmdb.hosts where node='${node}' and node_alias='${nodeAlias}'`
      }
      return new Promise((resolve, reject) => {
        sqlFindOne(params).then(
          (res) => {
            resolve(res)
          },
          (error) => {
            reject(error)
          }
        )
      })
    }
  }
}
</script>

<style lang="less" scoped>
</style>
